#include <string.h>
#include <iostream>

using std::cout;
using std::endl;

class Computer
{
public:
    Computer()
    : _brand(nullptr)
    , _price(0)
    //, _totalPrice(0)   //静态数据成员不能在初始化列表中进行初始化
    { 
        cout << "Computer()" << endl;   
    }

    Computer(const char * brand, double price)
    : _brand(new char[strlen(brand) + 1]())
    , _price(price)
    {
        cout << "Computer(const char*, double)" << endl;
        strcpy(_brand, brand);
        _totalPrice += _price;//记录总价信息
    }

    Computer(const Computer & rhs)
    : _brand(new char[strlen(rhs._brand) + 1]())
    , _price(rhs._price)
    {
        cout << "Computer(const Computer &)" << endl;
        strcpy(_brand, rhs._brand);
    }

    Computer & operator=(const Computer & rhs) {
        cout << "operator=()" << endl;
        if(this != &rhs){//自赋值
            delete [] _brand;
            _brand = new char[strlen(rhs._brand) + 1]();
            strcpy(_brand, rhs._brand);
            _price = rhs._price;
        }
        return *this;
    }

    ~Computer()
    {   
        cout << "~Computer()" << endl;  
        if(_brand) {
            delete [] _brand;//回收一个数组
            _brand = nullptr;
        }
    }

    void print() 
    {
        if(_brand) {
            cout << "brand:" << _brand << endl;
            cout << "price:" << _price << endl;
            cout << "total price:" << _totalPrice << endl;
        }
    }

private:
    static double _totalPrice;//被类的所有对象共享
    //const static int _x = 0;//ok
    char * _brand = nullptr;//64位系统一个指针占据的空间是8个字节
    double _price =0;
};

//静态数据成员要在类之外进行初始化, 而且不需要加上static关键字
//位于全局静态区
//static
double Computer::_totalPrice = 0;
//double Computer::_totalPrice = 1;
double totalprice = 0;


int main()
{
    //Q:静态数据成员是否占据对象的存储空间呢？
    //A: 静态数据成员不占据对象的存储空间,没有与对象放在一起
    cout << "sizeof(Computer):" << sizeof(Computer) << endl;
    Computer c1("Huawei", 6666);//栈区
    cout << "购买第一台电脑c1:" << endl;
    c1.print();
    cout << endl;

    Computer c2("Xiaomi", 7777);
    cout << "购买第二胎电脑c2:" << endl;
    c2.print();

    //被private修饰之后，也不能直接在类之外访问
    //cout << Computer::_totalPrice << endl;//error

    return 0;
}

